<?php
/**
 * Chat actions.
 *
 * @package    webmonstr
 * @subpackage Chat
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class ChatActions extends sfActions
{
  /**
   * Executes index action
   *
   */
      public function executeNomoney()
  {
  }


    public function executeMoney(sfWebRequest $request)
  {
      $ch = ChatroomPeer::retrieveByPK($request->getParameter('id'));
      if($ch)
          {
              if($ch->getWithVideo()==true)
                  {
                      $summa = sfConfig::get('app_cost_chat_video');
                      $level = 17;
                  }
                  else
                      {
                          $summa = sfConfig::get('app_cost_chat');
                          $level = 18;
                      }

              $pf = $this->getUser()->getProfile();
              if($pf->getAccount()<=0)
                  {
                      $this->nomoney = true;
                      $ch->delete();
                  }
                  else
                    {

                    $pa = new Payment ( );
                    $pa->setUserId ( $request->getParameter('u') );
                    $pa->setPaymentId ( $this->getUser ()->getAttribute ( 'user_id', null, 'sfGuardSecurityUser' ) );
                    $pa->setLevelId ( $level );
                    $pa->setSumma ( $summa );
                    $pa->setDirection ( 0 );
                    $pa->save ();


                    $pf->setAccount($pf->getAccount()-$summa);
                    $pf->save();
                    }
              $this->setLayout(false);
              sfConfig::set('sf_web_debug',false);
          }

  }

    public function executeWait_answer(sfWebRequest $request)
  {
      $this->from_user = $this->getUser()->getProfile();
      $this->user = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));
      $rez = $this->Check_answer($request->getParameter('id'),$this->from_user->getId());
      switch ($rez) {
                    case 1:
                        $this->rez = 1;
                        break;
                    case 2:
                        $this->rez = 2;
                        break;
                    case 3:
                        $this->rez = 3;
                        
                        break;
                   }
       $this->setLayout(false);
       sfConfig::set('sf_web_debug',false);
  }

    public function executeReject(sfWebRequest $request)
  {
     $this->setCancel($request->getParameter('id'));
  }

   public function executeDenite(sfWebRequest $request)
  {
    
  }


      public function executeDelete(sfWebRequest $request)
  {
     $ch = ChatroomPeer::retrieveByPK($request->getParameter('id'));
      if($ch)
          {
             $user_id = $ch->getToId();
             $ch->delete();
             $this->redirect('profile/show?id='.$user_id);
          }
          else
          {
               $this->redirect('mainpage/index');
          }
     
  }

   public function executeCall(sfWebRequest $request)
  {

        ////Проверка на заполненность профайла
  	if(!$this->getUser()->getProfile()->getFullProfile())
  	{
  	 $this->getUser ()->setFlash ( 'error', __('Вы не полностью заполнили профайл') );
  	 $this->redirect('profile/step2');
  	}
        ////


        
      $this->from_user = $this->getUser()->getProfile();
  
      ///проверяем счет
        if($this->from_user->getAccount()<=0 and $this->from_user->getGender()=='m') $this->redirect('chat/nomoney');
      ///

      $this->to_user   = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));
      $this->rez = $this->Check_answer($request->getParameter('id'),$this->from_user->getId());

  ////Проверка на бабу
  	if($this->from_user->getGender()=='w' and $this->to_user->getGender()=='w')
  	{
  	 $this->getUser ()->setFlash ( 'error', __('You can not call to other woman!') );
  	 $this->redirect('profile/myprofile');
  	}
        ////


      if($this->rez==2)
          {
                        $c = new Criteria();
                        $c->add(ChatroomPeer::FROM_ID,$this->from_user->getId());
                        $c->add(ChatroomPeer::TO_ID,$this->to_user->getId());
                        $c->add(ChatroomPeer::ACCEPT,true);
                        $c->add(ChatroomPeer::IS_ACTIVE, false);
                        //$c->add(ChatroomPeer::PUB, 1);
                        $ch = ChatroomPeer::doSelect($c);
                        foreach($ch as $h)
                            {
                                $h->delete();
                            }
                       $this->redirect('chat/call?id='.$this->to_user->getId());
          }
          else
              {
                  $this->ch = $this->Make_room($this->from_user->getId(), $this->to_user->getId());
              }
 
      // if(!$this->Make_room($from_user->getId(), $to_user->getId())) $this->redirect('chat/error');
  }

   public function executeAnswer(sfWebRequest $request)
  {
      
      if($request->getParameter('video')=='yes')
          {
              $this->setAnswer($request->getParameter('id'),true);
          }
          else
          {
              $this->setAnswer($request->getParameter('id'),false);
          }
      
      $this->ch = ChatroomPeer::retrieveByPK($request->getParameter('id'));
     if($this->ch)
              {
              $this->user = sfGuardUserPeer::retrieveByPK($this->ch->getFromId());
              $this->user_from =  sfGuardUserPeer::retrieveByPK($this->ch->getToId());
              //$this->ch->setIsActive(true);
              //$this->ch->setAccept(true);
              //$this->ch->save();
              }
              else
              {
                  $this->redirect('@home');
              }
  }

   


    public function executeError(sfWebRequest $request)
  {
     
  }


   public function executeCheck(sfWebRequest $request)
  {
      ///Проверяем вызов с чата
      if($this->getContext()->getUser()->isAuthenticated())
    {
        $user =  $this->getContext()->getUser()->getProfile();
        $c = new Criteria();
        $c->add(ChatroomPeer::TO_ID,$user->getId());
        $c->add(ChatroomPeer::ACCEPT,false);
        $c->add(ChatroomPeer::PUB,0);
        $cnt = ChatroomPeer::doCount($c);
        if($cnt>0)
            {
                $this->chat = ChatroomPeer::doSelectOne($c);
                $this->ret = true;
            }
            else
            {
                $this->ret = false;
            }
    }
      // $this->setLayout(false);
      // sfConfig::set('sf_web_debug',false);
       ///
  }


  public function executeWm()
  {

		/*
		 * проверяем на кол-во денег!
		 */

      if(!$this->getUser()->isAuthenticated())
    	{

			echo '<div style=" background:#FFFFCC; padding:0 10px; border:1px dashed #FF0000" align="center">
			<br />
			User is no authenicated!
			<br /><br />
			</div>';

			return sfView::NONE;
        }
        
        $_user_id=sfContext::getInstance()->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' );
    	$accountt = $this->getUser()->getProfile()->getAccount();
    	$gender = $this->getUser()->getProfile()->getGender();
    	
        

    	if($accountt<=0 and $gender=='m')
    	{

			echo '<div style=" background:#FFFFCC; padding:0 10px; border:1px dashed #FF0000" align="center">
			<br />
                        On your account - '.$accountt.' credits.<br />
			You don\'t have enought credits!
			<br /><br />
			</div>';
			
			return sfView::NONE;
    		
    		//$this->setFlash ( 'alert_message', __ ( 'У вас на счету недостаточно денег' ) );
			//$this->redirect ( 'Profile/swow?user_id='.$_user_id );

    	}



//echo "---".sfContext::getInstance()->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' );

 
	// You need to set these variables to be appropriate for your site and user.  Some will be provided by Userplane during account setup
	// If you have not received these values yet please contact Userplane at support@userplane.com or call (323) 938-4401
	$strFlashcomServer = "flashcom.alika-love-agency.userplane.com";		// The flashcom server: flashcom.yourcompany.userplane.com (from Userplane)
	$strDomainID = "alika-love-agency.com";								// The domain ID of this site: yourdomain.com (from Userplane)
	$strSessionGUID = sfContext::getInstance()->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' );									// The session identifier for the currently logged in user
	$strKey = "";													// Additional login information you may need passed
	$strInstanceID = "";											// The instance that you want this user to join.  If you are using the Webmessenger										// The instance that you want this user to join.  If you are using the Webmessenger
																	// with the Webchat or Userlist you will need to make sure the instanceID matches
																	// that of the Webchat or the Userlist for the IM windows to open automatically.

	// You will need to work on the sendCommand JavaScript function a few lines down to respond to any user clicks as you deem necessary

	$strDestinationUserID = $_GET["strDestinationUserID"];
	
	
       

	
?>

<html>
<head>
	<meta http-equiv=Content-Type content="text/html;  charset=ISO-8859-1">
	<title>Userplane AV Webmessenger</title>

	<script language="JavaScript">
	<!--
		function sendCommand( commandIn, valueIn )
		{
			if( commandIn == "focus" )
			{
				// DO NOT EDIT

				var wmObject = getWMObject();
				// only do the focus if we are sure it is not going remove focus from typing area
				if( wmObject != null && ( wmObject.focus != undefined || ( navigator.userAgent.indexOf( "MSIE" ) >= 0 && navigator.userAgent.indexOf( "Mac" ) >= 0 ) ) )
				{
					window.focus();
					wmObject.focus();
				}
			}
			else
			{
				// EDIT HERE: you will need to handle the following commands from the wm client
				if( commandIn == "viewProfile" )
				{
					if( valueIn == "-1" )
					{
						// view their own profile
						//alert(<?php echo( $strDestinationUserID ); ?>);
						
					}
					else
					{
						var userID = valueIn;
						// view userID's profile
						window.open("http://alika-love-agency.com/index.php/Profile/show/id/<?php echo( $strDestinationUserID ); ?>/","game","width=800,height=600,scrollbars=yes,resizable=yes,menubar=yes,location=yes,status=yes,directories=yes,toolbar=yes");
						
					}
				}
				else if( commandIn == "help" )
				{
					// view the help
						window.open("http://alika-love-agency.com/?action=faq&rasdel=17&fst=1","game","width=800,height=600,scrollbars=yes,resizable=yes,menubar=yes,location=yes,status=yes,directories=yes,toolbar=yes");
					
					
				}
				else if( commandIn == "buddyList" )
				{
					// view their buddy list
				}
				else if( commandIn == "preferences" )
				{
					// view the preferences
				}
				else if( commandIn == "addBuddy" )
				{
					var userID = valueIn;
					// respond to an add buddy click (XML has also been notified)
				}
				else if( commandIn == "block" )
				{
					// they blocked the user
				}
				else if( commandIn == "unblock" )
				{
					// they unblocked the user
				}
				else if( commandIn == "Connection.Success" )
				{
					// client successfully connected to server
				}
				else if( commandIn == "Connection.Failure" )
				{
					// client was disconnected from server
				}
				else if( commandIn == "Session.Timeout" )
				{
					// client's session was timed out
				}
				else if( commandIn == "Game.Open" )
				{
					openGameWindow( valueIn );
				}
			}
		}

		function focusIt()
		{
			window.focus();

			var wmObject = getWMObject();

			if( wmObject != null && wmObject.focus != undefined )
			{
				wmObject.focus();
			}
		}

		function getWMObject()
		{
			if(document.all)
			{
				return document.all["wm"];
			}
			else if(document.layers)
			{
				return document.wm;
			}
			else if(document.getElementById)
			{
				return document.getElementById("wm");
			}

			return null;
		}

		function wm_DoFSCommand( command, args )
		{
		}
		function openGameWindow( qs )
		{
			var newWindow = window.open("http://alika-love-agency.com/chatlite/games/?" + qs,"game","width=600,height=555,scrollbars=yes,resizable=yes,menubar=yes,location=no,status=no,directories=no,toolbar=no");

			if (newWindow == null)
			{
				alert( "Your popup blocker stopped the game window from opening" );
			}
		}

	//-->
	</script>

	<script language="VBScript">
	<!--
		//  Map VB script events to the JavaScript method - Netscape will ignore this...
		//  Since FSCommand fires a VB event under ActiveX, we respond here
		Sub wm_FSCommand(ByVal command, ByVal args)
	  		call wm_DoFSCommand(command, args)
		end sub
	-->
	</script>
</head>
<body onLoad="javascript: focusIt();" bgcolor="#ffffff" bottommargin="0" leftmargin="0" marginheight="0" marginwidth="0" rightmargin="0" topmargin="0">

	<?php
		if( $strDestinationUserID != "" )
		{
			$strSwfServer = "swf.userplane.com";
			$strApplicationName = "Webmessenger";
			$strLocale = "english";
			?>

			<script type="text/javascript" src="http://alika-love-agency.com/webmessenger/flashobject.js"></script>

			<!---
				The content of this div should hold whatever HTML you would like to show in the case that the
				user does not have Flash installed.  Its contents get replaced with the Flash movie for everyone
				else.
			--->
			<div id="flashcontent">
				<strong>You need to upgrade your Flash Player by clicking <a href="http://www.macromedia.com/go/getflash/" target="_blank">this link</a>.</strong><br><br><strong>If you see this and have already upgraded we suggest you follow <a href="http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_14157" target="_blank">this link</a> to uninstall Flash and reinstall again.</strong>
			</div>

			<script type="text/javascript">
				// <![CDATA[

				var fo = new FlashObject("http://<?php echo( $strSwfServer ); ?>/<?php echo( $strApplicationName ); ?>/ic.swf", "wm", "100%", "100%", "6", "#ffffff", false, "best");
				fo.addParam("scale", "noscale");
				fo.addParam("menu", "true");
				fo.addParam("salign", "LT");
				fo.addVariable("server", "<?php echo( $strFlashcomServer ); ?>");
				fo.addVariable("swfServer", "<?php echo( $strSwfServer ); ?>");
				fo.addVariable("applicationName", "<?php echo( $strApplicationName ); ?>");
				fo.addVariable("domainID", "<?php echo( $strDomainID ); ?>");
				fo.addVariable("instanceID", "<?php echo( $strInstanceID ); ?>");
				fo.addVariable("sessionGUID", "<?php echo( $strSessionGUID ); ?>");
				fo.addVariable("key", "<?php echo( $strKey ); ?>");
				fo.addVariable("locale", "<?php echo( $strLocale ); ?>");
				fo.addVariable("destinationMemberID", "<?php echo( $strDestinationUserID ); ?>");
				fo.addVariable("resizable", "true");
				fo.write("flashcontent");
				

				// COPYRIGHT Userplane 2006 (http://www.userplane.com)
				// WM version 1.8.13

				// ]]>
			</script>

			<?php
		}
	?>

</div>

</body>
</html>
  	<?php

  	/*
  	//usleep(30000000);
  	
  	  	echo "------".$strSessionGUID;
  	
  	$c = new Criteria();
    $c->add(ChatPeer::MASTER_ID, $strSessionGUID);
  	$c->addDescendingOrderByColumn('id');
  	$c->setLimit(1);
  	$items = ChatPeer::doSelect($c);	

  	foreach($items as $items)
  	{
  		echo "---------------".$items->getType();
  		$items->setType('owner');
  		
  	}
  
  	$items->save();  	
	*/

        ///записываем вызов
 


    return sfView::NONE;
  }


  /*
  *   Создание комнаты
   */

  public function Make_room($from_id, $to_id)
  {
   
        $c = new Criteria();
        $c->add(ChatroomPeer::FROM_ID,$from_id);
        $c->add(ChatroomPeer::TO_ID,$to_id);
        $c->add(ChatroomPeer::PUB,0);
        $cnt = ChatroomPeer::doCount($c);
        if($cnt==0)
            {
                $ch = new Chatroom();
                $ch->setFromId($from_id);
                $ch->setToId($to_id);
                $ch->save();
                return $ch;
            }
            else
            {
                $ch = ChatroomPeer::doSelectOne($c);
                return $ch;
            }
  }

   /*
  *   Положительный ответ
   */

  public function setAnswer($id,$with_video=false)
  {
      $ch = ChatroomPeer::retrieveByPK($id);
     // echo $id; die;
                if($ch)
                    {
                        $ch->setIsActive(true);
                        $ch->setWithVideo($with_video);
                        $ch->setAccept(true);
                        $ch->save();
                    }
                return true;
  }


    /*
  *   Отрицательный ответ
   */

  public function setCancel($id)
  {
                $ch =  ChatroomPeer::retrieveByPK($id);
                $ch->setIsActive(false);
                $ch->setAccept(true);
                $ch->setPub(1);
                $ch->save();
                return true;
  }

    /*
  *   проверка ответа вызываемого
   */

  public function Check_answer($target_id,$from_id)
  {

        $c = new Criteria();
        $c->add(ChatroomPeer::TO_ID,$target_id);
        $c->add(ChatroomPeer::FROM_ID,$from_id);
        //$c->add(ChatroomPeer::PUB,0);
       
        $ch = ChatroomPeer::doSelectOne($c);
        if($ch)
            {
                if($ch->getAccept()==true and $ch->getIsActive()==false)
                        {
                            // отказ
                            return 2;
                        }
                elseif($ch->getAccept()==false)
                    {
                            //// Ожидание ответа
                            return 1;
                    }

                     elseif($ch->getAccept()==true and $ch->getIsActive()==true)
                         {
                             /// согласие
                             return 3;
                         }
                     else
                         {
                             return 1;
                         }
            }
            else
                {
                    return 1;
                }
  }



}
